package com.android.shop;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.android.shop.R;
import com.android.shop.common.StringUtils;
import com.android.shop.constant.MyConstantID;
import com.android.shop.ui.HomePageActivity;
import com.android.shop.ui.LoginActivity;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.Toast;

/**
 * 应用程序启动类：显示欢迎界面并跳转到主界面
 */
public class AppStart extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final View view = View.inflate(this, R.layout.welcome_layout, null);
		setContentView(view);

		// 渐变展示启动屏
		AlphaAnimation aa = new AlphaAnimation(0.3f, 1.0f);
		aa.setDuration(2000);
		view.startAnimation(aa);
		aa.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationEnd(Animation arg0) {
				redirectTo();
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationStart(Animation animation) {
			}
		});
	}

	/**
	 * 跳转到...
	 */
	private void redirectTo() {

		SharedPreferences sp = getSharedPreferences(MyConstantID.SP_NAME,
				Activity.MODE_PRIVATE);
		String loginname = sp.getString("loginname", "");
		String expires = sp.getString("expires", "");
		if (!loginname.equals("") && !expires.equals("")) {
			try {
				SimpleDateFormat df = new SimpleDateFormat(
						"yyyy-MM-dd hh:mm:ss");
				Date expiresDate = df.parse(expires);
				Date nowDate = new Date();
				long diff = expiresDate.getTime() - nowDate.getTime();
				if (diff > 0) {
					Toast.makeText(getApplicationContext(), "正在自动登录...",
							Toast.LENGTH_SHORT).show();
					gotoHome();
				} else {
					gotoLogin();
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			gotoLogin();
		}
	}
	
	public void gotoLogin(){
		Intent intent = new Intent(this, LoginActivity.class);
		startActivity(intent);
		finish();
	}
	
	public void gotoHome(){
		Intent intent = new Intent(this, HomePageActivity.class);
		startActivity(intent);
		finish();
	}
}